package com.ququ.syb.commission.service;

import com.ququ.common.result.Result;
import com.ququ.syb.commission.fegin.PayChannelFegin;
import com.ququ.syb.commission.pubs.PublicServiceApi;
import com.ququ.syb.commission.redis.RedisDao;
import com.ququ.syb.common.constant.PayChannelStatusConstant;
import com.ququ.syb.common.constant.RedisKeyConstant;
import com.ququ.syb.common.constant.WithdrawTypeConstant;
import com.ququ.syb.common.pojo.PayChannel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Service
public class CommissionService {
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private PayChannelFegin payChannelFegin;
    @Autowired
    private PublicServiceApi publicServiceApi;
//    @Autowired
//    private PublicServiceFegin publicServiceFegin;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public Result<Double> getPayCommissionRate(String paychannelid, String appcode, String accountid, String partner){
        Jedis jedis = redisDao.getJedis();
        try {
            PayChannel payChannel = payChannelFegin.getPayChannel(paychannelid).getData();
            if (payChannel == null || payChannel.getStatus() != PayChannelStatusConstant.NORMAL)
                return new Result<>(-1, "通道号不存在或通道不可用");
            //优先级1：账户费率设置
            if (StringUtils.isNotBlank(accountid) && jedis.hexists(RedisKeyConstant.ACCOUNT_PAYCHANNEL_COMMISSION+accountid,paychannelid)){
                Double accountCommission = Double.valueOf(jedis.hget(RedisKeyConstant.ACCOUNT_PAYCHANNEL_COMMISSION+accountid,paychannelid));
                return new Result<>(accountCommission);
            }
            //优先级2：服务商费率设置
            if (StringUtils.isNotBlank(partner) && jedis.hexists(RedisKeyConstant.PARTNER_PAYCHANNEL_COMMISSION+partner,paychannelid)){
                Double partnerCommission = Double.valueOf(jedis.hget(RedisKeyConstant.PARTNER_PAYCHANNEL_COMMISSION+partner,paychannelid));
                return new Result<>(partnerCommission);
            }
            //优先级3：应用费率设置
            if (StringUtils.isNotBlank(appcode) && jedis.hexists(RedisKeyConstant.APPLICATION_PAYCHANNEL_COMMISSION+appcode,paychannelid)){
                Double applicationCommission = Double.valueOf(jedis.hget(RedisKeyConstant.APPLICATION_PAYCHANNEL_COMMISSION+appcode,paychannelid));
                return new Result<>(applicationCommission);
            }
            //优先级4：通道默认手续费
            return new Result<>(payChannel.getCustomercommissionrate().doubleValue());
        }finally {
            redisDao.close(jedis);
        }
    }


    public Result<Long> getPayCommission(Long amount, String paychannelid, String appcode, String accountid, String partner){
        Jedis jedis = redisDao.getJedis();
        try {
            PayChannel payChannel = payChannelFegin.getPayChannel(paychannelid).getData();
            if (payChannel == null || payChannel.getStatus() != PayChannelStatusConstant.NORMAL)
                return new Result<>(-1, "通道号不存在或通道不可用");
            //优先级4：通道默认手续费
            Double commissionRate = payChannel.getCustomercommissionrate()!=null?payChannel.getCustomercommissionrate().doubleValue():0d;
            //优先级3：应用费率设置
            if (StringUtils.isNotBlank(appcode) && jedis.hexists(RedisKeyConstant.APPLICATION_PAYCHANNEL_COMMISSION+appcode,paychannelid)){
                commissionRate = Double.valueOf(jedis.hget(RedisKeyConstant.APPLICATION_PAYCHANNEL_COMMISSION+appcode,paychannelid));
            }
            //优先级2：服务商费率设置
            if (StringUtils.isNotBlank(partner) && jedis.hexists(RedisKeyConstant.PARTNER_PAYCHANNEL_COMMISSION+partner,paychannelid)){
                commissionRate = Double.valueOf(jedis.hget(RedisKeyConstant.PARTNER_PAYCHANNEL_COMMISSION+partner,paychannelid));
            }
            //优先级1：账户费率设置
            if (StringUtils.isNotBlank(accountid) && jedis.hexists(RedisKeyConstant.ACCOUNT_PAYCHANNEL_COMMISSION+accountid,paychannelid)){
                commissionRate = Double.valueOf(jedis.hget(RedisKeyConstant.ACCOUNT_PAYCHANNEL_COMMISSION+accountid,paychannelid));
            }
            Long commission = new BigDecimal(amount).multiply(new BigDecimal(commissionRate)).setScale(0,BigDecimal.ROUND_HALF_UP).longValue();
            //通道为固定费率
            if (payChannel.getCustomercommissionfixed() != null && payChannel.getCustomercommissionfixed() != 0)
                commission = payChannel.getCustomercommissionfixed().longValue();
            //通道有封顶费率,超出封顶
            if (payChannel.getCustomerceilinglimit() != null && payChannel.getCustomerceilinglimit() != 0 && commission > payChannel.getCustomerceilinglimit().longValue())
                commission = payChannel.getCustomerceilinglimit().longValue();
            return new Result<>(commission);
        }finally {
            redisDao.close(jedis);
        }
    }


    public Result<Long> getPayCostCommission(Long amount, String paychannelid){
        PayChannel payChannel = payChannelFegin.getPayChannel(paychannelid).getData();
        if (payChannel == null || payChannel.getStatus() != PayChannelStatusConstant.NORMAL)
            return new Result<>(-1, "通道号不存在或通道不可用");
        Long costCommission = payChannel.getChannelcommissionrate() != null? new BigDecimal(amount).multiply(payChannel.getChannelcommissionrate()).setScale(0,BigDecimal.ROUND_HALF_UP).longValue(): 0l;
        if(payChannel.getChannelcommissionfixed() != null && payChannel.getChannelcommissionfixed() != 0)
            costCommission = payChannel.getChannelcommissionfixed().longValue();
        if (payChannel.getCeilinglimit() != null && payChannel.getCeilinglimit() != 0 && costCommission > payChannel.getCeilinglimit().longValue())
            costCommission = payChannel.getCeilinglimit().longValue();
        if (payChannel.getFloorlimit() != null && payChannel.getFloorlimit() != 0 && costCommission < payChannel.getFloorlimit())
            costCommission = payChannel.getFloorlimit().longValue();
        return new Result<>(costCommission);
    }


    /**
     * 获取通道提现客户手续费
     * @param amount
     * @param paychannelid
     * @param appcode
     * @param accountid
     * @return
     */
    public Result<Long> getWithdrawCommission(Long amount,String paychannelid,String appcode,String accountid){
        PayChannel payChannel = payChannelFegin.getPayChannel(paychannelid).getData();
        if (payChannel == null || payChannel.getStatus() != PayChannelStatusConstant.NORMAL)
            return new Result<>(-1, "通道号不存在或通道不可用");
        Jedis jedis = redisDao.getJedis();
        try{
            Long commission = payChannel.getCustomerwithdrawcommission()==null?0L:payChannel.getCustomerwithdrawcommission().longValue();
            if (StringUtils.isNotBlank(appcode) && jedis.hexists(RedisKeyConstant.APPLICATION_PAYCHANNEL_WITHDRAW_COMMISSION+appcode,paychannelid))
                commission = Long.parseLong(jedis.hget(RedisKeyConstant.APPLICATION_PAYCHANNEL_WITHDRAW_COMMISSION+appcode,paychannelid));
            if (StringUtils.isNotBlank(accountid) && jedis.hexists(RedisKeyConstant.ACCOUNT_PAYCHANNEL_WITHDRAW_COMMISSION+accountid,paychannelid))
                commission = Long.parseLong(jedis.hget(RedisKeyConstant.ACCOUNT_PAYCHANNEL_WITHDRAW_COMMISSION+accountid,paychannelid));
            //亿企通周末特殊处理
            if (payChannel.getPaychannelname().startsWith("易宝亿企通")){
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DATE,1);
                if (!publicServiceApi.isWorkingday(simpleDateFormat.format(calendar.getTime()))){
                    commission = new BigDecimal(amount * 0.0002d).longValue();  //周末出款，0.02% + 0.2元手续费(结算只有一笔，不予计算)
                }else
                    commission = 0L;
            }
            if (payChannel.getWithdrawcommissiontype() == 3)
                return getWithdrawCostCommission(amount,paychannelid,0);
            else
                return new Result<>(commission);
        }finally {
            redisDao.close(jedis);
        }
    }


    /**
     * 获取通道提现手续费成本
     * @param amount
     * @param paychannelid
     * @param withdrawtype
     * @return
     */
    public Result<Long> getWithdrawCostCommission(Long amount,String paychannelid,Integer withdrawtype){
        PayChannel payChannel = payChannelFegin.getPayChannel(paychannelid).getData();
        if (payChannel == null || payChannel.getStatus() != PayChannelStatusConstant.NORMAL)
        return new Result<>(-1, "通道号不存在或通道不可用");
        Long commission = 0L;
        switch (payChannel.getWithdrawcommissiontype()){
            case 1:     //固定费率
                commission = payChannel.getWithdrawcommission().longValue();
                break;
            case 2:     //中茂通道模式： D0和假节日D1(走D0)百分比+保底，工作日D1只有保底
            case 3:
                if (withdrawtype == WithdrawTypeConstant.D0){
                    commission = new BigDecimal(amount * payChannel.getWithdrawcommission().doubleValue()).longValue();
                    if (commission < payChannel.getMinwithdrawcommission())
                        commission = payChannel.getMinwithdrawcommission().longValue();
                }else if (withdrawtype == WithdrawTypeConstant.D1){
                    commission = payChannel.getMinwithdrawcommission().longValue();
                }
                break;
        }
        //亿企通周末特殊处理
        if (payChannel.getPaychannelname().startsWith("易宝亿企通")){
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,1);
            if (publicServiceApi.isWorkingday(simpleDateFormat.format(new Date()))){
                commission = new BigDecimal(amount * 0.0002d).longValue();  //周末出款，0.02% + 0.2元手续费(结算只有一笔，不予计算)
            }else
                commission = 0L;
        }
        return new Result<>(commission);
    }


}
